package com.e2edour.web.controller;

import com.e2edour.facade.WeiXinManagerFacade;
import com.e2edour.facade.abc.CommonResponse;
import com.e2edour.facade.enums.ResCodeEnum;
import com.e2edour.facade.req.WeiXinCheckSignatureReq;
import com.e2edour.facade.req.WeiXinMsgReq;
import com.e2edour.facade.res.WeiXinMsgRes;
import com.e2edour.runtime.properties.AppContextConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.IOException;
import java.io.StringReader;

/**
 * <p>
 *
 * @author King
 * @since 2017/1/13
 */
@Controller
@RequestMapping("wechatapi")
public class WeiXinController {

    @Autowired
    private WeiXinManagerFacade weiXinManagerFacade;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @ResponseBody
    @RequestMapping(method = {RequestMethod.POST})
    public String handler(HttpServletRequest request) throws IOException, JAXBException {
        try {
            ServletInputStream in = request.getInputStream();
            StringBuilder xmlMsg = new StringBuilder();
            byte[] b = new byte[4096];
            for (int n; (n = in.read(b)) != -1; ) {
                xmlMsg.append(new String(b, 0, n, "UTF-8"));
            }
            logger.info("微信请求参数:\n{}", xmlMsg.toString());
            JAXBContext jaxbContext = JAXBContext.newInstance(WeiXinMsgReq.class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            WeiXinMsgReq wexinReq = (WeiXinMsgReq) unmarshaller.unmarshal(new StringReader(xmlMsg.toString()));
            WeiXinMsgRes res = weiXinManagerFacade.handlerMsg(wexinReq);
            if (ResCodeEnum.success().id() == res.getResCode()) {
                logger.info("返回微信消息:\n{}", res.getDataObject().getMsg());
                return res.getDataObject().getMsg();
            }
            return "error";
        } catch (IOException e) {
            logger.error("handler IOException:", e);
        } catch (JAXBException e) {
            logger.error("handler JAXBException:", e);
        } catch (Exception e) {
            logger.error("handler Exception:", e);
        }
        return "error";
    }

    @RequestMapping(method = {RequestMethod.GET})
    @ResponseBody
    public String checkSignature(String signature, String timestamp, String nonce, String echostr) {
        logger.info("开始微信验证功能:signature{}-timestamp{}-nonce{}-echostr{}", signature, timestamp, nonce, echostr);
        WeiXinCheckSignatureReq req = new WeiXinCheckSignatureReq();
        req.setSignature(signature);
        req.setTimestamp(timestamp);
        req.setNonce(nonce);
        req.setSystem(AppContextConfig.getAppName());
        CommonResponse res = weiXinManagerFacade.checkSignature(req);
        //if (res.getResCode() == ResCodeEnum.success().id()) {
        return echostr;
        //}
        //return "error";
    }
}
